import { decrypt, encrypt } from '../crypto'

//加密密钥，默认为空字符串，代表不加密，localstorage中存储明文。注意：更改密钥会导致之前的数据解析失败！！！
const cryptoSecret = ''
//如果想加密，可以对cryptoSecret赋值。或者解开下方注释，使用配置文件中的密钥
// import { getServiceEnvConfig } from '~/.env-config'
// const { cryptoSecret } = getServiceEnvConfig(import.meta.env)

function createLocalStorage(): LocalStg {
    /** 默认缓存期限为7天 */
    const DEFAULT_CACHE_TIME = 60 * 60 * 24 * 7

    /**
     * 设置Localstorage缓存
     * @param key
     * @param value
     * @param expire - 过期时间，单位秒，不传则默认为7天。传null则永不过期
     */
    function set<K = string, V = any>(
        key: K,
        value: V,
        expire: number | null = DEFAULT_CACHE_TIME
    ) {
        console.debug('开始缓存', key, expire)
        const storageData: StorageData<V> = {
            value,
            expire: expire !== null ? new Date().getTime() + expire * 1000 : null
        }
        const json = encrypt(storageData, cryptoSecret)
        window.localStorage.setItem(key as string, json)
    }

    /**
     * 根据key获取Localstorage缓存
     * @param key
     */
    function get<K = string, V = any>(key: K) {
        const json = window.localStorage.getItem(key as string)
        if (json) {
            let storageData: StorageData<V> | null = null
            try {
                storageData = decrypt(json, cryptoSecret)
            } catch {
                // 防止解析失败
            }
            if (storageData) {
                const { value, expire } = storageData
                // 在有效期内直接返回
                if (expire === null || expire >= Date.now()) {
                    return value as V
                }
            }
            remove(key)
            return null
        }
        return null
    }

    /**
     * 根据key移除Localstorage缓存
     * @param key
     */
    function remove<K = string>(key: K) {
        window.localStorage.removeItem(key as string)
    }

    /**
     * 清空Localstorage中所有缓存
     */
    function clear() {
        window.localStorage.clear()
    }

    return {
        set,
        get,
        remove,
        clear
    }
}

export const localStg = createLocalStorage()
